// src/pages/EditProfile.jsx
import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { Form, Input, Button, Upload, Cascader } from 'antd';
import { Toast } from 'antd-mobile';
import { motion } from 'framer-motion';
import { useAuthStore } from '../store/authStore';
import { fadeIn } from '../styles/animations';
import { validatePassword } from '../utils/validation';
import { calculateConstellation } from '../utils/constellation';
import { cityData } from '../utils/cityData';
import { clearAuthData } from '../utils/storage';
import { PlusOutlined } from '@ant-design/icons';

const EditProfile = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [form] = Form.useForm();
  const { updateProfile, loading, error, clearErrors, getUserInfo } = useAuthStore();
  const [fileList, setFileList] = useState([]);
  const [userInfo, setUserInfo] = useState(null);
  const [constellation, setConstellation] = useState('');

  // 获取用户信息并填充表单
  useEffect(() => {
    const fetchUserData = async () => {
      try {
        const data = await getUserInfo();
        setUserInfo(data);
        
        // 填充表单数据
        form.setFieldsValue({
          password: '',
          passwordConfirm: '',
          city: data.city ? [data.city] : undefined,
          birth: data.birth,
        });
        
        // 设置星座
        if (data.birth) {
          setConstellation(calculateConstellation(data.birth));
        }
        
        // 如果有头像，设置文件列表
        if (data.avatar) {
          setFileList([{
            uid: '-1',
            name: 'avatar',
            status: 'done',
            url: `${import.meta.env.VITE_API_URL}/api/files/${data.collectionId}/${data.id}/${data.avatar}`,
          }]);
        }
      } catch (err) {
        Toast.show({
          content: '获取用户信息失败',
          position: 'center',
        });
      }
    };

    fetchUserData();
  }, [form, getUserInfo]);

  // 监听错误
  useEffect(() => {
    if (error) {
      Toast.show({
        content: error,
        position: 'center',
      });
      clearErrors();
    }
  }, [error, clearErrors]);

  // 头像上传前的处理
  const beforeUpload = (file) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      Toast.show({
        content: '只能上传图片文件！',
        position: 'center',
      });
      return false;
    }
    // 将文件添加到文件列表，确保包含 originFileObj
    setFileList([{
      uid: file.uid,
      name: file.name,
      status: 'done',
      originFileObj: file,
    }]);
    return false; // 阻止默认上传行为
  };

  // 生日变化时更新星座
  const handleBirthChange = (e) => {
    const birthDate = e.target.value;
    if (birthDate) {
      const newConstellation = calculateConstellation(birthDate);
      setConstellation(newConstellation);
    } else {
      setConstellation('');
    }
  };

  // 提交表单
  const onFinish = async (values) => {
    try {
      // 密码校验
      if (!validatePassword(values.password)) {
        Toast.show({
          content: '密码至少需要8位字符',
          position: 'center',
        });
        return;
      }
      // 旧密码
      if (!values.oldPassword) {
        Toast.show({
          content: '请输入旧密码',
          position: 'center',
        })
      }
      
      // 密码确认校验
      if (values.password !== values.passwordConfirm) {
        Toast.show({
          content: '两次输入的密码不一致',
          position: 'center',
        });
        return;
      }
      
      // 城市校验
      if (!values.city || values.city.length < 1) {
        Toast.show({
          content: '请选择城市',
          position: 'center',
        });
        return;
      }

      // 构造 FormData
      const formData = new FormData();
      
      // 必填字段
      formData.append('oldPassword', values.oldPassword);
      formData.append('password', values.password);
      formData.append('passwordConfirm', values.passwordConfirm);
      formData.append('city', values.city[0]); // 城市
      formData.append('birth', values.birth);
      formData.append('constellation', calculateConstellation(values.birth));

      // 头像文件（可选）
      if (fileList.length > 0 && fileList[0].originFileObj) {
        const file = fileList[0].originFileObj;
        const fileName = Math.random().toString(36).substring(2, 8) + '.png';
        formData.append('avatar', file, fileName);
      }

      await updateProfile(formData);
      Toast.show({
        content: '更新成功',
        position: 'center',
      });
      clearAuthData(); // 清除localStorage中的token和用户数据
      navigate('/login');
    } catch (err) {
      console.error('更新失败:', err);
    }
  };

  // 自定义样式
  const formItemStyle = {
    marginBottom: '0.15rem',
  };

  const labelStyle = {
    fontSize: '0.14rem',
    fontWeight: '500',
    color: '#333',
    marginBottom: '0.05rem',
  };

  const inputStyle = {
    fontSize: '0.14rem',
    height: '0.32rem',
    borderRadius: '0.04rem',
  };

  const cascaderStyle = {
    fontSize: '0.14rem',
    height: '0.32rem',
    borderRadius: '0.04rem',
  };

  const uploadStyle = {
    fontSize: '0.12rem',
  };

  return (
    <motion.div
      className="flex flex-col bg-white mobile-container"
      style={{
        height: '100vh',
        overflow: 'hidden',
      }}
      initial="hidden"
      animate="visible"
      exit="exit"
      variants={fadeIn}
    >
      <div 
        className="flex-grow flex flex-col justify-center mobile-scroll"
        style={{
          padding: '0.2rem',
          height: 'calc(100vh - 0.4rem)',
          overflowY: 'auto',
          overflowX: 'hidden',
        }}
      >
        <div className="mt-[0.3rem] w-full max-w-[2.8rem] mx-auto">
          <div className="bg-white py-[0.3rem] px-[0.15rem]">
            <Form
              form={form}
              layout="vertical"
              onFinish={onFinish}
              size="small"
            >
              <Form.Item
                name="oldPassword"
                label="旧密码"
                rules={[{ required: true, message: '请输入旧密码' }]}
                style={formItemStyle}
                labelCol={{ style: labelStyle }}
              >
                <Input 
                  placeholder="请输入旧密码" 
                  type="password" 
                  style={inputStyle} 
                />
              </Form.Item>

              <Form.Item
                name="password"
                label="新密码"
                style={formItemStyle}
                labelCol={{ style: labelStyle }}
                rules={[
                  { required: true, message: '请输入新密码' },
                  { 
                    validator: (_, value) => {
                      if (validatePassword(value)) return Promise.resolve();
                      return Promise.reject(new Error('密码至少需要8位字符'));
                    }
                  }
                ]}
              >
                <Input 
                  placeholder="请输入新密码" 
                  type="password" 
                  style={inputStyle} 
                />
              </Form.Item>

              <Form.Item
                name="passwordConfirm"
                label="确认新密码"
                style={formItemStyle}
                labelCol={{ style: labelStyle }}
                rules={[
                  { required: true, message: '请确认新密码' },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (getFieldValue('password') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('两次输入的密码不一致'));
                    },
                  }),
                ]}
              >
                <Input 
                  placeholder="再次输入新密码" 
                  type="password" 
                  style={inputStyle} 
                />
              </Form.Item>

              <Form.Item
                name="city"
                label="所在城市"
                rules={[{ required: true, message: '请选择城市' }]}
                style={formItemStyle}
                labelCol={{ style: labelStyle }}
              >
                <Cascader 
                  options={cityData} 
                  placeholder="请选择城市" 
                  style={cascaderStyle}
                  dropdownStyle={{ fontSize: '0.12rem' }}
                />
              </Form.Item>

              <Form.Item
                name="birth"
                label="生日"
                rules={[{ required: true, message: '请输入生日' }]}
                style={formItemStyle}
                labelCol={{ style: labelStyle }}
              >
                <Input 
                  placeholder="请输入生日 (YYYY-MM-DD)" 
                  type="date" 
                  style={inputStyle}
                  onChange={handleBirthChange}
                />
              </Form.Item>


              <Form.Item
                label="头像（可选）"
                style={formItemStyle}
                labelCol={{ style: labelStyle }}
              >
                <Upload
                  beforeUpload={beforeUpload}
                  listType="picture-card"
                  fileList={fileList}
                  showUploadList={{ showPreviewIcon: true, showRemoveIcon: true }}
                  onRemove={() => setFileList([])}
                  style={uploadStyle}
                >
                  {fileList.length === 0 && (
                    <div style={{ fontSize: '0.12rem' }}>
                      <PlusOutlined />
                      <div style={{ marginTop: 4, fontSize: '0.12rem' }}>上传</div>
                    </div>
                  )}
                </Upload>
              </Form.Item>

              <Button 
                block 
                type="primary" 
                htmlType="submit" 
                loading={loading} 
                size="small" 
                className="mt-[0.2rem]" 
                style={{ 
                  fontSize: '0.16rem',
                  height: '0.36rem',
                  borderRadius: '0.04rem'
                }}
              >
                保存修改
              </Button>
            </Form>

            <div className="mt-[0.2rem] text-center">
              <Button 
                type="link" 
                onClick={() => navigate('/wu')}
                className="text-blue-500 hover:text-blue-700 text-[0.14rem]"
              >
                返回个人中心
              </Button>
            </div>
          </div>
        </div>
      </div>
    </motion.div>
  );
};

export default EditProfile;
